
package program;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.DBManager;
import model.Program;
import model.ProgramRate;
import model.Station;

/**
 *
 * @author Team-2
 */
public class EditProgramForm extends javax.swing.JFrame {

    /**
     * Creates new form EditProgramForm
     */
    public EditProgramForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
    }
    
    public EditProgramForm(Program p,  boolean readOnly) {
        em = DBManager.em;
        program1=p;
        this.readOnly = readOnly;
        if ( !(em.getTransaction().isActive()) ){
            em.getTransaction().begin();
        }
        initComponents();
        //org.jdesktop.observablecollections.ObservableCollections.observableList(customerQuery.getResultList());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        stationModel = new model.Station();
        programModel = program1;
        stationQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select s from Station s");
        stationList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(stationQuery.getResultList());
        stationBoxRenderer = new avenue.StationBoxRenderer();
        programRateQuery = em.createQuery("select pr from ProgramRate pr where pr.stationId=:station and pr.programId=:program").setParameter("station", stationModel).setParameter("program", programModel);
        programRateList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(programRateQuery.getResultList());
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        programNameText = new javax.swing.JTextField();
        stationCombo = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jprogramRateTable = new javax.swing.JTable();
        jLabel9 = new javax.swing.JLabel();
        programIdTextField1 = new javax.swing.JTextField();
        bonusTransitsText = new javax.swing.JTextField();
        monthlyDemandsText = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();

        stationBoxRenderer.setText("stationBoxRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Διαχείριση Προγράμματος");
        setResizable(false);

        jLabel1.setText("Σταθμός: ");

        jLabel2.setText("Διόδια που εισπράττονται ανά κατηγορία οχήματος");

        jLabel8.setText("Πρόγραμμα: ");

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jButton4.setText("Άκυρο");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        jButton5.setText("Εφαρμογή");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programModel, org.jdesktop.beansbinding.ELProperty.create("${name}"), programNameText, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        stationCombo.setRenderer(stationBoxRenderer);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, stationList, stationCombo, "stationBoxBinding");
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, stationModel, org.jdesktop.beansbinding.ObjectProperty.create(), stationCombo, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"), "stationBinding");
        bindingGroup.addBinding(binding);

        stationCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stationComboActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programRateList, jprogramRateTable, "");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${categoryId.description}"));
        columnBinding.setColumnName("Κατηγορία Οχήματος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${rate}"));
        columnBinding.setColumnName("Αξία Διέλευσης");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jprogramRateTable);

        jLabel9.setText("Περιγραφή Προγράμματος: ");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programModel, org.jdesktop.beansbinding.ELProperty.create("${description}"), programIdTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programModel, org.jdesktop.beansbinding.ELProperty.create("${bonusTransits}"), bonusTransitsText, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        bonusTransitsText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bonusTransitsTextActionPerformed(evt);
            }
        });

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programModel, org.jdesktop.beansbinding.ELProperty.create("${monthlyDemands}"), monthlyDemandsText, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        monthlyDemandsText.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                monthlyDemandsTextKeyReleased(evt);
            }
        });

        jLabel3.setText("Όριο Μην. Διελεύσεων:");

        jLabel4.setText("Αρ. Δωρεάν Διελεύσεων:");

        jLabel6.setText("*");

        jLabel7.setText("*");

        jLabel10.setText("*");

        jLabel11.setText("*");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stationCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel8)
                        .addGap(8, 8, 8)
                        .addComponent(programNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel11))
                    .addComponent(jLabel2)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel9)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(monthlyDemandsText, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(3, 3, 3)
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4)
                                .addGap(7, 7, 7)
                                .addComponent(bonusTransitsText))
                            .addComponent(programIdTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(256, 256, 256)
                            .addComponent(jButton4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton5))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(stationCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel6)
                        .addComponent(programNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel8)
                        .addComponent(jLabel11))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(programIdTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bonusTransitsText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(monthlyDemandsText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton5)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
 
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,false);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
       }
       this.setVisible(false); 
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
       
       if ( validateFields() ) {  
            MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,true);
            for (WindowListener l : this.getWindowListeners()) {
                l.windowClosed(we);
           }
           this.setVisible(false); 
       }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void stationComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stationComboActionPerformed
   
        if(stationList.size()>0 && stationCombo.getSelectedIndex()!=-1){
            station1=(Station)(stationList.get(stationCombo.getSelectedIndex()));
            programRateQuery = em.createQuery("select pr from ProgramRate pr " +
                                              "where pr.stationId=:station and pr.programId=:program")
                                  .setParameter("station", station1)
                                  .setParameter("program", programModel);
            List<ProgramRate> list3 = programRateQuery.getResultList();
            if (list3.size()>0){
                programRateList.clear();
                for (ProgramRate pr : list3){
                 programRateList.add(pr);  
               }
            } 
        }
    }//GEN-LAST:event_stationComboActionPerformed

    private void bonusTransitsTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bonusTransitsTextActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_bonusTransitsTextActionPerformed

    private void monthlyDemandsTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_monthlyDemandsTextKeyReleased

    }//GEN-LAST:event_monthlyDemandsTextKeyReleased

    /**
     * Check if the given number is numeric or not
     * @param num
     * @return 
     */
    public boolean isIntNumber(String num){
        try{
            Integer.parseInt(num);
        } catch(NumberFormatException nfe) {
            return false;
        }
        return true;
    }    
    
    
 /**
 * Validate some required fields
 * @return 
 */    
  private boolean validateFields() {
        
       String  message;
       boolean res = true;
       String programName = programNameText.getText();
       //stationCombo
       String monthlyDemands = monthlyDemandsText.getText();
       String bonusTransits = bonusTransitsText.getText();
       
        //required customer name
        if ( programName.isEmpty() ) {
             message = "Δεν συμπληρώσατε όνομα προγράμματος, παρακαλώ ξαναπροσπαθήστε";
             JOptionPane.showMessageDialog(this, message, "Προσοχή", 0); 
             return false;
        }    
       
        //required customer surname
        if ( monthlyDemands.isEmpty() || !isIntNumber(monthlyDemands) ) {
             message = "Δεν είναι σωστά συμπληρωμένο το όριο μηνιαίων διελεύσεων, παρακαλώ ξαναπροσπαθήστε";
             JOptionPane.showMessageDialog(this, message, "Προσοχή", 0); 
             return false;
        }         
       
        //required customer afm
        if ( bonusTransits.isEmpty() || !isIntNumber(bonusTransits) ) {
             message = "Δεν είναι σωστά συμπληρωμένος ο αριθμός δωρεάν διελέυσεων, παρακαλώ ξαναπροσπαθήστε";
             JOptionPane.showMessageDialog(this, message, "Προσοχή", 0); 
             return false;
        }  
       
      return res;
    }    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EditProgramForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField bonusTransitsText;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jprogramRateTable;
    private javax.swing.JTextField monthlyDemandsText;
    private javax.swing.JTextField programIdTextField1;
    private model.Program programModel;
    private javax.swing.JTextField programNameText;
    private java.util.List<ProgramRate> programRateList;
    private javax.persistence.Query programRateQuery;
    private avenue.StationBoxRenderer stationBoxRenderer;
    private javax.swing.JComboBox stationCombo;
    private java.util.List<Station> stationList;
    private model.Station stationModel;
    private javax.persistence.Query stationQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    ProgramRate pr;
    Program program1;
    Station station1;
    JFrame thisFrame;
    boolean readOnly;
}
